package Doem;

import java.util.PriorityQueue;
import java.util.TimerTask;
import java.util.concurrent.Executors;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    private long time;


    public MyTimerTask(Runnable task, long time){
        this.task=task;
        this.time=System.currentTimeMillis()+time;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);
        //return (int)(o.time-this.time);
    }
    public void run(){
        task.run();
    }

}
class MyTimer{
    private PriorityQueue<MyTimerTask> queue=new PriorityQueue<>();
    public void schedule(Runnable task,long delay){
        synchronized (this){
            MyTimerTask timerTask=new MyTimerTask(task,delay);
            queue.offer(timerTask);
            this.notify();
        }
    }
    public MyTimer(){
        //创建一个线程，负责执行队列中的任务
        Thread t=new Thread(()->{
            try{
                while (true){
                    synchronized (this) {
                        while (queue.isEmpty()) {
                            this.wait();
                        }
                        MyTimerTask task=queue.peek();
                        if(System.currentTimeMillis()<task.getTime()){
                            this.wait(task.getTime()-System.currentTimeMillis());
                        }else {
                            queue.poll();
                            task.run();
                        }
                    }
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
        t.start();
    }
}
public class Timer {
    public static void main(String[] args) {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello,3000");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello,2000");
            }
        },2000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello,1000");
            }
        },1000);
        Executors.newScheduledThreadPool(4);
    }
}
